package com.tsinghuabigdata.edu.ddmath.receive;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.AppUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.data.JPushLocalNotification;

/**
 * Created by 28205 on 2016/7/5.
 */
public class JPushNotifyHelper {

    private static final String TAG = "JPushHelper";
    public static final String CUSTOM_MESSAGE_RECEIVER_ACTION = "com.tsinghuabigdata.edu.ddmath.custom.message.opened";


    public static void setShowingNotifyNum(Context context, int num){
        JPushInterface.setLatestNotificationNumber(context, num);
    }
    public static void showNotify4SelfdefMsg2(Context context, Bundle bundle) {

        JPushLocalNotification ln = new JPushLocalNotification();
        ln.setBuilderId(0);
        ln.setContent(bundle.getString(JPushInterface.EXTRA_MESSAGE));
        ln.setTitle(context.getString(R.string.app_name));
        ln.setNotificationId(555);
        ln.setBroadcastTime(System.currentTimeMillis());

        //解析消息字段属性
        String res = bundle.getString(JPushInterface.EXTRA_EXTRA);
        JSONObject jsonObject = null;
        int msgTypeId = 0;
        String  remark = null;
        String source = null;
        String msgType = null;
        String rowKey = null;
        try {
            jsonObject = new JSONObject(res);
            msgTypeId = jsonObject.getInt("msgTypeId");
            try{
                msgType = jsonObject.getString("msgType");
            }catch (Exception e){
                AppLog.d( e.toString() );
            }
            try {
                source = jsonObject.getString("source");
            }catch (Exception e){
                AppLog.d( e.toString() );
            }

            try {
                rowKey = jsonObject.getString("rowKey");
            }catch (Exception e){
                AppLog.d( e.toString() );
            }
            remark = jsonObject.getString("remark");
        } catch (Exception e) {
            AppLog.d( e.toString() );
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msgTypeId", msgTypeId);
        map.put("msgType", msgType);
        map.put("remark", remark);
        map.put("source", source);
        map.put("rowKey", rowKey);
        JSONObject json = new JSONObject(map);
        ln.setExtras(json.toString());
        JPushInterface.addLocalNotification(context, ln);
    }

    /**
     * 发送通知
     *
     * @param context
     * @param bundle
     */
    public static void showNotify4SelfdefMsg(Context context, Bundle bundle) {
        //从配置缓存里取出用户设定的模式
//        String notifyMode = AccountUtils.getNotifySettingMode();
        int notifyModeCode;
//        if (notifyMode.equals(AppConst.VIBRATION_NOTIFY_MODE)) {
//            notifyModeCode = Notification.DEFAULT_VIBRATE;
//        } else if (notifyMode.equals(AppConst.VOICE_NOTIFY_MODE)) {
//            notifyModeCode = Notification.DEFAULT_SOUND;
//        } else {
            notifyModeCode = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND;
//        }
        //新建通知
        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        //通知点击时，发送广播，注意设置注册广播的action动作
        Intent intent = new Intent();
        intent.putExtra(JPushInterface.EXTRA_EXTRA, bundle.getString(JPushInterface.EXTRA_EXTRA));
        intent.setAction(CUSTOM_MESSAGE_RECEIVER_ACTION);
        //使用UUID保证requestCode唯一性，避免多个通知的PendingIntent事件冲突
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, UUID.randomUUID().hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setTicker(context.getString(R.string.app_name))
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(bundle.getString(JPushInterface.EXTRA_MESSAGE))
                .setDefaults(notifyModeCode)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));

        Notification notification = builder.build();

        //发送通知，注意通知的ID属性按需设置为不同的值，保证能够实现多条通知的显示，同时，统一类型的通知只显示一条，实时更新即可， 如同一个人的聊天消息
        nManager.notify(bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID), notification);
    }


    //打开自定义的Activity
    public static void jumpToActivity(Context context, Class cls) {
        ActivityManager.RunningTaskInfo topTask = AppUtils.getTopTask(context);
        String packageName = AppUtils.getPackageInfo(context).packageName;
        if (AppUtils.isTopActivity(topTask, packageName, cls.getName())) {
            AppLog.d("cls : " + cls.getName() + "  在最前端");
        } else {
            Intent i = new Intent(context, cls);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        }
    }

    public static void enterApp(Context context) {
        //TODO
//        LoginInfo loginInfo = AccountUtils.getLoginUser();
//        if (null == loginInfo) {
//            //用户未登录
//            Log.i(TAG, "用户未登录");
//            jumpToActivity(context, InitActivity.class);
//        } else {
//            jumpToActivity(context, AppMainActivity.class);
//        }
    }

    /*public static void setJpushAlias(Context context) {
        String accountId = AccountUtils.getLoginUser().getUser().getAccount().getAccountId();
        Log.d(TAG, "setJpushAlias accountid "+ accountId);
        JPushInterface.setAlias(context, accountId, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                Log.d(TAG, "gotResult " + i + " s : " + s);
            }
        });
    }*/
}